var productViewModel, geocoder;

$(document).ready(function() {
	var jcarousel = $('.jcarousel').jcarousel();
	productViewModel = new productViewModel(jcarousel, productDto, questions);
	ko.applyBindings(productViewModel, $("#productDetail-container")[0]);
});

function productViewModel(jcarousel, product, questions) {
	var self = this;
	
	self.id = product["id"];
	self.name = product["name"];
	self.subtitle = product["subtitle"];
	self.description = product["description"];
	self.category = product["category"];
	self.categoryId = product["categoryId"];
	self.selectedImage = ko.observable();
	self.stock = ko.observable(product["quantity"]);
	self.stockQuantity = ko.computed(function() {
		return self.stock() + " unidades";
	});
	self.hasStock = ko.computed(function() {
		return self.stock() > 0;
	});
	
	self.price = product["price"];
	self.negotiablePrice = product["negotiablePrice"];
	self.marketId = product["marketId"];
	self.marketName = product["marketName"];
	self.marketPhone = product["marketPhone"];
	self.marketEmail = product["marketEmail"];
	self.marketAddress = product["marketAddress"];
	self.isMarketEnable = product["marketEnable"];
	self.smallMarketImagePath = getImagePath('image/marketThumb', product["marketImagePath"], "small");
	self.mediumMarketImagePath = getImagePath('image/marketThumb', product["marketImagePath"], "medium");
	self.userFullName = product["userName"] + " " + product["userSurname"];
	self.isOwner = isOwner;
	self.visibleMap = product.marketLatitude != undefined && product.marketLongitude != undefined;
	
	self.productImages = ko.observableArray([]);
	
	/* Questions */
	self.questions = ko.observableArray(($.map(questions, function (question) { return new Question(question, self.isOwner); })));

	self.newQuestion = ko.observable();
	self.createQuestion = function() {
		if(self.newQuestion()) {
			getService("question/canAsk", { }, self.onCanAskSuccess,
				function(jqXHR, textStatus, errorThrown) {
					verifyAuthentication(jqXHR.responseText, self.onCanAskSuccess);
				}
			);
		} else {
			alert("Por favor escribe una pregunta");
		}
	};
	
	self.onCanAskSuccess = function() {
		getService("question/askProduct", { "productId": self.id, "question" : self.newQuestion() }, self.askSuccess, 
				function(error) {
			alert("Lo sentimos, no puedes realizar esta pregunta");
		});
	};
	
	self.askSuccess = function(question) {
		self.newQuestion("");
		self.questions.unshift(new Question(question, self.isOwner));
	};
	
	self.showQuestions = function(questions) {
		$(questions).show();
	};
	/* End Questions */
	
	if(product.images.length > 0) {
		self.productImages(product.images);
	} else {
		var defaultImage = {isPrincipal : true, path : 'defaultProduct.jpg'};
		self.productImages([defaultImage]);
	}
	
	self.selectedImage(self.productImages()[0]);
	
	self.afterRenderImages = function(element, data){
		jcarousel.jcarousel('reload');
	};
	
	self.imageUrl = ko.computed(function(){
//		return getImagePath('image/productThumb', self.selectedImage().path, "medium");
		return getCompletePath('imageHandler/productThumb') + '?fileName=' + self.selectedImage().path + '&w=410&h=270';
	});
	
	self.fancyImageUrl = ko.computed(function(){
//		return getImagePath('image/productThumb', self.selectedImage().path, "large");
		return getCompletePath('imageHandler/productThumb') + '?fileName=' + self.selectedImage().path + '&w=1024&h=768';
	});
	
	//JQZOOM
	self.getGallery = function(image){
//		var smallImg = getImagePath('image/productThumb', image.path, "medium");
//		var largeImg = getImagePath('image/productThumb', image.path, "large");
		
		var smallImg = getCompletePath('imageHandler/productThumb') + '?fileName=' + image.path + '&w=410&h=270';
		var largeImg = getCompletePath('imageHandler/productThumb') + '?fileName=' + image.path + '&w=1024&h=768';
		
		var gallery = "{ gallery: 'gal1', smallimage: '" + smallImg + "', largeimage: '" + largeImg + "'}";
		return gallery;
	};
	
	self.getSmallImage = function(image){
		return getCompletePath('imageHandler/productThumb') + '?fileName=' + image.path + '&w=106&h=66';
	};
	
	self.goToProductsWithPreselectedCategory = function() {
		redirect('product/products/' + self.categoryId);
	};
	
	self.goToMarket = function() {
		redirect('market/detail/' + self.marketId + '/' + self.marketName.replaceAll(" ", "-"));
	};
	
	self.confirmPurchase = function() {
		getService("product/purchaseProduct", { "productId" : self.id }, function(response) {
			$('#confirmPurchaseModal').modal('hide');
			if(response == 'BUYING_ERROR') {
				alert("No puedes comprar este producto");
				location.reload();
			} else {
				$('#purchasedProductInfoModal').modal('show');
				self.stock(self.stock() - 1);
			}
		});
	};
	
	self.onPurchaseSuccess = function(response) {
		$('#confirmPurchaseModal').modal('show');
	};
	
	self.purchase = function() {
		if(self.stock() > 0) {
			getService("product/canPurchaseProduct", { }, self.onPurchaseSuccess,
				function(jqXHR, textStatus, errorThrown) {
					verifyAuthentication(jqXHR.responseText, productViewModel.purchase);
				}
			);
		}
	};
	
	self.setMap = function(){
		var lat = product.marketLatitude ? product.marketLatitude : -34.6028;
		var lng = product.marketLongitude ? product.marketLongitude : -58.3816;
		var latlng = new google.maps.LatLng(lat, lng);
		var mapOptions = {
			center: latlng,
			zoom: 15,
			mapTypeId: google.maps.MapTypeId.ROADMAP
		};
		var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
	    new google.maps.Marker({
	        map: map, 
	        position: latlng
	    });
	};
	
	self.setMap();
};

